package com.service.business.support;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.business.order.dto.ProductHashRateComboCar;
import com.service.business.order.dto.ProductOtherCar;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年11月12日</dd>
 * </dl>
 *
 * @author
 */
@Component
public class ShoppingCar {

    @Autowired
    private MemCache memCache;

    private static String COMBO_KEY = "order:combo:";

    private static String PRODUCT_KEY = "order:product:";

    /**
     * 购物车:算力套餐
     *
     * @param productHashRateComboCar
     * @param uid
     */
    public void addHashRateCombo2car(ProductHashRateComboCar productHashRateComboCar, Integer uid) {
        String jsonObject = JSONObject.toJSONString(productHashRateComboCar);
        memCache.setNoExpire(COMBO_KEY + uid, jsonObject);
    }

    public void addProduct2ProductCar(ProductOtherCar productOtherCar, Integer uid) {
        List<ProductOtherCar> shoppingCar = getProductFromCar(uid);
        boolean isAddNum = false;
        for (ProductOtherCar item : shoppingCar) {
            if (ObjectUtils.nullSafeEquals(item, productOtherCar.getId())) {
                item.setOrderNum(item.getOrderNum() + 1);
                isAddNum = true;
            }
        }
        if (!isAddNum) {
            shoppingCar.add(productOtherCar);
        }
        String jsonObject = JSONObject.toJSONString(shoppingCar);
        memCache.setNoExpire(PRODUCT_KEY + uid, jsonObject);
    }

    public void addProduct2ProductCar(List<ProductOtherCar> productOtherCar, Integer uid) {
        String jsonObject = JSONObject.toJSONString(productOtherCar);
        memCache.setNoExpire(PRODUCT_KEY + uid, jsonObject);
    }

    public ProductHashRateComboCar getComboFromCar(Integer uId) {
        String json = memCache.get(COMBO_KEY + uId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSONObject.parseObject(json, ProductHashRateComboCar.class);
    }

    public List<ProductOtherCar> getProductFromCar(Integer uId) {
        String json = memCache.get(PRODUCT_KEY + uId);
        if (StringUtils.isEmpty(json)) {
            return new ArrayList<>();
        }
        return JSONArray.parseArray(json, ProductOtherCar.class);
    }


    /**
     * 清空算力套餐购物车
     *
     * @param uid
     */
    public void removeHashRateComboFromCar(Integer uid) {
        memCache.delete(COMBO_KEY + uid);
    }

    /**
     * 清空产品购物车
     *
     * @param uid
     */
    public void removeProductFromCar(Integer uid) {
        memCache.delete(PRODUCT_KEY + uid);
    }


}
